﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using TiTi.tea.Api.Models;

namespace TiTi.tea.Api.Controllers
{
    
    public class ImagesController : ApiController
    {
        /// <summary>
        /// 图片上传（form表单上传）
        /// </summary>
        /// <returns></returns>
   
        public Result Post()
        {
            List<string> images = new List<string>();
            // 文件保存目录路径
            const string saveTempPath = "\\Images\\";
            //当前目录
            var dirTempPath = HttpContext.Current.Server.MapPath("/");

            string newRoot = dirTempPath + saveTempPath; ;// 当前项目绝对路径

            //判断是否有当前图片文件夹
            if (!Directory.Exists(newRoot))
            {
                //创建存储文件夹
                Directory.CreateDirectory(newRoot);
            }
            //处理上传
            HttpFileCollection files = HttpContext.Current.Request.Files;
            foreach (var f in files.AllKeys)
            {
                HttpPostedFile file = files[f];
                if (!string.IsNullOrEmpty(file.FileName))
                {
                    //文件后缀//获取文件格式，拓展名
                    var fileExtension = Path.GetExtension(file.FileName).ToLower();

                    //保存的文件名称(以保存时间命名)
                    var saveName = DateTime.Now.Ticks + fileExtension;

                    //保存文件到指定路径（完整路径）
                    file.SaveAs(newRoot + saveName);

                    // 添加返回结果
                    images.Add("/Images/" + saveName);

                }
            }

            return Result.Success(images);
        }

    }
}